<?php
/**
 * User: Nicho
 * Date: 17-3-31
 * Time: AM 08:10
 */

namespace Admin\Controller;
use Think\UploadFile;


class DataController extends AdminController
{
    //数据表
    private $dataModel;
    //达客id表
    private $signModel;

    //单位表
    private $unitModel;
    //数据配置表
    private $dataTmpModel;
    //省市区表
    public function __construct(){
        parent::__construct();
        $this->signModel = M('core_dksign');
        $this->unitModel = M('core_unit');
        $this->dataModel = M('core_data');
        $this->dataTmpModel = M('core_data_tmp');
        $this->dataModel->create();
        $this->dataTmpModel->create();
    }
    const MODEL_NAME = 'Data@:';

    //接口列表
    public function index()
    {
        // $a = rand(10,99);
        // $b = microtime();
        // $c = explode(' ', $b);
        // var_dump ($c[1]);
        // $d = substr($c[1],-5);
        // $e = substr($c[0]*100000000, 0,3);
        // var_dump($d);
        // var_dump($e);
        // var_dump ($d.$e.$a);exit;
        // echo $a;
        if(I('keyword')){
            $keyword = I('keyword');
            $map['batch'] = array('like','%'.$keyword.'%');
            $this->assign('keyword',$keyword);
        }
        // if(I('sort')){
        //     $sort = I('sort');
        //     if($sort == 'recycle'){
        //         $map['status'] = -1;

        //         $this->assign('recycle','【回收站】');
        //     }
        // }else{
        //     $sort = 'normal';
        //     $map['status'] = array('egt', 0);
        // }
        $model = D('core_data');
        $map['status'] = array('neq',-1);
        $totalCount = $model->where($map)->count();
        $page = new \Think\Page($totalCount,10);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list = $model->where($map)->limit($limit)->order('id desc')->select();
        foreach ($list as $key => $value) {
            $list[$key]['uname'] = $this->unitModel->where('id = '.$value['unit'])->getField('title');
            $list[$key]['gname'] = M('auth_group')->where('id = '.$value['group'])->getField('title');
        }
        $this->assign('_list',$list);
        $this->assign('_page',$page->show());
        $this->meta_title = '数据中心';
        $this->display(self::MODEL_NAME.'Data/index'); 
        
    }
      public function impor()
    {
        //上传xls
        
      if (IS_POST) {
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 3145728 ;// 设置附件上传大小
        $upload->allowExts  = array('xls');// 设置附件上传类型
        $upload->savePath =  './Uploads/Data/'.date('Ymd').'/';// 设置附件上传目录
        if(!$info = $upload->upload()) {// 上传错误提示错误信息
            $this->error($upload->getErrorMsg());
        }else{// 上传成功 获取上传文件信息
            $info =  $upload->getUploadFileInfo();
        }
        $info[0]['savepath']=substr($info[0]['savepath'], 1); 
        $filename = $info[0]['savepath'].$info[0]['savename'];
        $para = explode(',',I('unit')); //同时获取地区id和单位id，分别生成达客id和外键用
        $para['group'] = I('group');
        $batch = $this->showExcel($filename,$para);
        $this->success('成功,正在跳转……',U('Data/yulan',array('batch'=>$batch)));//导入成功之后跳转页面。
      }else{
        //单位列表
        $unitList = $this->unitModel->where('status = 1')->select();
        $this->assign('unitList',$unitList);
        //角色列表
        $groupList = M('auth_group')->where('status = 1 and id <> 1')->select();
        $this->assign('groupList',$groupList);

        $this->display(self::MODEL_NAME.'Data/impor');
      }
    }
    //预览
    public function yulan()
    {   

        $tmpModel = M('core_data_tmp');
        if(IS_POST){
            $tmp = $tmpModel->where("batch = '".I('batch')."'")->select();
            if($this->dataModel->addAll($tmp)){$this->success('导入成功',U('Data/index'));}else{$this->error('导入失败');}
        }else{
            $list = $tmpModel->where("batch = '".I('batch')."'")->order('dkyey_core_data_tmp.id desc')->join('dkyey_core_unit ON dkyey_core_data_tmp.unit = dkyey_core_unit.id')->field('dkyey_core_unit.title,dkyey_core_data_tmp.realname,dkyey_core_data_tmp.depart,dkyey_core_data_tmp.batch,dkyey_core_data_tmp.id')->select();
            $this->assign('_list',$list);
            $this->display(self::MODEL_NAME.'Data/yulan');
        }
    }

    //数据管理-因为导入的文件，所以需要一个文件类来打开该文件
    public function showExcel($filename,$para)
    {
        header('Content-type:text/html;charset=utf8');
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $PHPReader=new \PHPExcel_Reader_Excel5();
        //载入文件
        $PHPExcel=$PHPReader->load('.'.$filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=2;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $arr[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
            }
        }
        /////存入临时表
        $TempModel = D('core_data_tmp');
        $batch = md5($filename);
        foreach ($arr as $key => $value) {
            $dksign = $this->getDKsign($para[1]);
            $data = array(  
                  'realname'=>(string)trim($value['A']),
                  'depart'=>(string)trim($value['B']),
                  'unit'=>$para[0],
                  'status'=>1,
                  'create_time'=>time(),
                  'dksign'=>$dksign,
                  'batch'=>$batch,
                  'group'=>$para['group']
                  );
            $tmp[] = $data;
        }
        if($TempModel->addAll($tmp)){
            return $batch;//返回批次号，便于查找。
        }else{
            echo "导入失败";
        }
    }
    
    //达客标识
    public function dakeSign()
    {
        if(I('keyword')){
            $keyword = I('keyword');
            $map['title'] = array('like','%'.$keyword.'%');
            $this->assign('keyword',$keyword);
        }
        // if(I('sort')){
        //     $sort = I('sort');
        //     if($sort == 'recycle'){
        //         $map['status'] = -1;

        //         $this->assign('recycle','【回收站】');
        //     }
        // }else{
        //     $sort = 'normal';
        //     $map['status'] = array('egt', 0);
        // }
        $model = D('core_dksign');
        $map['status'] = array('neq',-1);
        $totalCount = $model->where($map)->count();
        $page = new \Think\Page($totalCount,10);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list = $model->where($map)->limit($limit)->order('id desc')->select();
        $this->assign('_list',$list);
        $this->assign('_page',$page->show());
        $this->meta_title = '数据中心';
        $this->display(self::MODEL_NAME.'Data/dkSign'); 
        
    }
    //添加/编辑表示
    public function updateSign()
    {
        if(IS_POST){
            $unit = explode(',',I('unit')); //同时获取地区id和单位id，分别生成达客id和外键用
            $b = explode(' ', microtime()); //生成达客id用
            switch (I('a_type')) {
                case 'add':
                    $this->dataModel->unit = $unit[0];
                    $this->dataModel->status = 1;
                    $this->dataModel->dksign = $this->getDKsign($unit[1]);
                    $this->dataModel->create_time = time();
                    $result = $this->dataModel->add();
                    break;
                case 'edit':
                    $this->dataModel->unit = $unit[0];
                    $this->dataModel->update_time = time();
                    $result = $this->dataModel->where('id = '.I('id'))->save();
                    break;
            }
            if($result){
                $this->success('更新成功',U('index'));
            }else{
                $this->error('更新失败');
            }
        }else{
            //单位列表
            $unitList = $this->unitModel->where('status = 1')->select();
            $this->assign('unitList',$unitList);
            //角色列表
            $groupList = M('auth_group')->where('status = 1 and id <> 1')->select();
            $this->assign('groupList',$groupList);

            $data = $this->dataModel->where('id = '.I('id'))->find();
            $this->assign('data',$data);
            $this->assign('a_type',I('a_type'));
            $this->display(self::MODEL_NAME.'Data/updateSign');
        }
    }
    //流水导出
    public function output(){

        header('Content-type:text/html;charset=utf8');
        import("Org.Util.PHPExcel");
        $resultPHPExcel = new \PHPExcel(); //一定要加跟杠，不然报错 
        if(I('batch')){
            $map['batch'] = array('like','%'.I('batch').'%');
        }
        $map['status'] = array('neq',-1);
        $list = D('core_data')->where($map)->select();
        $resultPHPExcel->getActiveSheet()->setCellValue('A1', '识别号'); 
        $resultPHPExcel->getActiveSheet()->setCellValue('B1', '姓名');
        $resultPHPExcel->getActiveSheet()->setCellValue('C1', '年级'); 
        $resultPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);  
        $resultPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);  
        $resultPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);  
        $i = 2; 
        foreach($list as $item){ 
            $resultPHPExcel->getActiveSheet()->setCellValue('A'.$i,$item['dksign']); 
            $resultPHPExcel->getActiveSheet()->setCellValue('B'.$i,$item['realname']); 
            $resultPHPExcel->getActiveSheet()->setCellValue('C'.$i,$item['depart']); 
            $i ++; 
        }
        //设置导出文件名 
        $outputFileName = 'data.xls'; 
        $xlsWriter = new \PHPExcel_Writer_Excel5($resultPHPExcel); 
        //ob_start(); ob_flush(); 
        header("Content-Type: application/force-download"); 
        header("Content-Type: application/octet-stream"); 
        header("Content-Type: application/download"); 
        header('Content-Disposition:inline;filename="'.$outputFileName.'"'); 
        header("Content-Transfer-Encoding: binary"); 
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
        header("Pragma: no-cache"); 
        $xlsWriter->save( "php://output" );
    }
    //设置状态
     public function setStatus()
    {
        $ids = I('request.id');
        $model = I('request.model');
        if(!$ids)$this->error('无可操作数据!');
        $map['id'] = array('in',$ids);
        $method = I('request.method');
        $model_object = D($model);
        switch ($method) {
            case 'resume':
                $model_object->status = 1;
                $result = $model_object->where($map)->save();
                if($result){
                    $this->success('激活成功!');
                }else{
                    $this->error('激活失败!');
                }
                break;
            case 'forbid':
                $model_object->status = 2;
                $result = $model_object->where($map)->save();
                if($result){
                    $this->success('禁用成功!');
                }else{
                    $this->error('禁用失败!');
                }
                break;
            case 'delete':
                $model_object->status = -1;
                $result = $model_object->where($map)->save();
                if($result){
                    $this->success('删除成功!');
                }else{
                    $this->error('删除失败!');
                }
                break;
            case 'recover':
                $model_object->status = 0;
                $result = $model_object->where($map)->save();
                if($result){
                    $this->success('恢复成功!');
                }else{
                    $this->error('恢复失败!');
                }
                break;
            case 'destory':
                $model_object->status = -2;
                $result = $model_object->where($map)->save();
                if($result){
                    $this->success('彻底删除成功!');
                }else{
                    $this->error('彻底删除失败!');
                }
                break;
            default:
                $this->error('系统参数错误!');
                break;
        }
    }
    //获得达客id
    public function getDKsign($unit)
    {
        $d['dksign'] = create_DKsign($unit);
        $d['create_time'] = time();
        $result = M('core_dksign')->add($d);
        if(!$result) {
            getDKsign($unit);
        }
        return $d['dksign'];
    }
}